/*全局组件,自定义指令,挂载全局方法*/
/*这就是插件*/
import xysSkeleton from "@/components/library/xys-skeleton.vue";
import xysSwiper from "@/components/library/xys-swiper.vue";
import xysMore from "@/components/library/xys-more.vue";
import defaultImg from '@/assets/images/default.png'
import xysBreadItem from "@/components/library/xys-bread-item.vue";
import xysBread from "@/components/library/xys-bread.vue";
import {defineAsyncComponent} from "vue";
import Message from "@/components/library/Message";
/*
 **全局注册组件
 ** 放在components/global文件夹下
 */
// todo 官方地址：https://cn.vitejs.dev/guide/features.html#glob-import
const components = import.meta.glob('./global/*.vue',{eager:true}); // 异步方式

export default function install(app){
    //     在app上挂载   app提供component directive 分别挂载组件和指令
    app.component('xys-skeleton',xysSkeleton)
    app.component('xys-swiper',xysSwiper)
    app.component('xys-more',xysMore)
    app.component('xys-bread',xysBread)
    app.component('xys-bread-item',xysBreadItem)

    // 批量注册全局组件
    // for (const [key, value] of Object.entries(components)) {
    //     const name = key.slice(key.lastIndexOf('/') + 1, key.lastIndexOf('.'));
    //     app.component(name, value);
    // }
    //     挂载自定义指令
    defineDirective(app)
//     挂载全局属性
    app.config.globalProperties.$message = Message
}



const defineDirective = (app) => {
//   图片懒加载指令
    app.directive('lazy', {
        mounted (el, binding) {
            const observer = new IntersectionObserver(([{ isIntersecting }]) => {
                if (isIntersecting) {
                    observer.unobserve(el)
                    el.onerror = () => {
                        el.src = defaultImg
                    }
                    el.src = binding.value
                }
            }, {
                threshold: 0.01
            })
            observer.observe(el)
        }
    })
}
